<template>
  <div class="vocabulary-management">
    <div class="header">
      <h1>{{ moduleTitle }}管理</h1>
      <div class="header-buttons">
        <el-button type="danger" :disabled="selectedWords.length === 0" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="info" @click="downloadTemplate">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
        <el-button type="warning" @click="showTemplateHelp">
          <el-icon><QuestionFilled /></el-icon>
          模板说明
        </el-button>
        <el-upload
          class="excel-uploader"
          :http-request="customUpload"
          :show-file-list="false"
          accept=".xlsx,.xls"
          :before-upload="beforeExcelUpload"
          :on-success="handleExcelUploadSuccess"
          :on-error="handleExcelUploadError"
        >
          <el-button type="success">
            <el-icon><Upload /></el-icon>
            Excel导入
          </el-button>
        </el-upload>
        <el-button type="primary" @click="handleAddWord">
          <el-icon><Plus /></el-icon>
          添加词语
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.keyword"
        placeholder="请输入词语内容搜索"
        style="width: 300px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="searchWords">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 表格数据 -->
    <el-table 
      :data="wordList" 
      style="width: 100%" 
      v-loading="loading" 
      @selection-change="handleSelectionChange"
      v-if="wordList.length > 0"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="word" label="词语" width="120" />
      <el-table-column prop="partOfSpeech" label="词性" width="100" />
      <el-table-column prop="definition" label="解释" min-width="200" show-overflow-tooltip />
      <el-table-column prop="examples" label="例子" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          <span>{{ row.examples }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="synonyms" label="近义" width="120" show-overflow-tooltip />
      <el-table-column prop="antonyms" label="反义" width="120" show-overflow-tooltip />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button size="small" @click="viewWord(row)">查看</el-button>
            <el-button size="small" @click="editWord(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteWord(row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <div class="no-data" v-else>
      <el-empty description="暂无词汇数据">
        <el-button type="primary" @click="handleAddWord">添加词语</el-button>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="wordList.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑词语对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑词语' : '添加词语'"
      width="600px"
    >
      <el-form :model="wordForm" :rules="rules" ref="wordFormRef" label-width="80px">
        <el-form-item label="词语" prop="word">
          <el-input v-model="wordForm.word" />
        </el-form-item>
        <el-form-item label="词性" prop="partOfSpeech">
          <el-select v-model="wordForm.partOfSpeech" placeholder="请选择词性">
            <el-option label="名词" value="名词" />
            <el-option label="动词" value="动词" />
            <el-option label="形容词" value="形容词" />
            <el-option label="副词" value="副词" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="解释" prop="definition">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="definitionEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 200px; overflow-y: hidden;"
              v-model="wordForm.definition"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleDefinitionCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="例子" prop="examples">
          <div style="border: 1px solid #dcdfe6; border-radius: 4px;">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="examplesEditorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 150px; overflow-y: hidden;"
              v-model="wordForm.examples"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleExamplesCreated"
            />
          </div>
          <div class="example-tip">
            <el-text type="info" size="small">例句不超过200字</el-text>
          </div>
        </el-form-item>
        <el-form-item label="近义" prop="synonyms">
          <el-input v-model="wordForm.synonyms" placeholder="请输入近义词，多个词用逗号分隔" />
        </el-form-item>
        <el-form-item label="反义" prop="antonyms">
          <el-input v-model="wordForm.antonyms" placeholder="请输入反义词，多个词用逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看词语详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="词语详情"
      width="600px"
      destroy-on-close
    >
      <div class="word-detail">
        <div class="word-header">
          <h2 class="word-title">
            {{ currentWord.word }}
          </h2>
        </div>

        <el-divider />

        <div class="detail-section">
          <div class="detail-item">
            <label>词性：</label>
            <span class="detail-content">{{ currentWord.partOfSpeech }}</span>
          </div>

          <div class="detail-item definition-item">
            <label>解释：</label>
            <div class="detail-content definition-content">
              {{ currentWord.definition }}
            </div>
          </div>

          <div class="detail-item examples-item">
            <label>例子：</label>
            <div class="detail-content">
              <el-card
                class="example-card"
                shadow="hover"
              >
                <template #header>
                  <div class="example-header">
                    <span>例子</span>
                  </div>
                </template>
                {{ currentWord.examples }}
              </el-card>
            </div>
          </div>

          <div class="detail-item" v-if="currentWord.synonyms">
            <label>近义：</label>
            <span class="detail-content">{{ currentWord.synonyms }}</span>
          </div>

          <div class="detail-item" v-if="currentWord.antonyms">
            <label>反义：</label>
            <span class="detail-content">{{ currentWord.antonyms }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Upload, Download, QuestionFilled } from '@element-plus/icons-vue';
import { batchDeleteVocabulary, importVocabulary, downloadVocabularyTemplate } from '@/api/vocabulary';
import type { FormInstance } from 'element-plus';
import type { VocabularyWord, VocabularyQueryParams } from '@/types/vocabulary';

// 富文本编辑器相关导入
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { createEditorRef, getEditorConfig, getToolbarConfig, createEditorCallback } from '@/utils/editorUtils';

interface Props {
  moduleTitle: string;
  apiModule: any;
  moduleType: string; // 新增 moduleType 属性
}

const props = defineProps<Props>();

// Excel上传相关函数
const beforeExcelUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过2MB！');
    return false;
  }
  return true;
};

const handleExcelUploadSuccess = (response: any) => {
  if (response.code !== 200) {
    ElMessage.error(response.message || '导入失败');
  } else {
    ElMessage.success(`成功导入${response.data}个词语`);
    getWordList(); // 刷新列表
  }
};

const handleExcelUploadError = (error: any) => {
  ElMessage.error(error.message || '文件上传失败，请重试');
  console.error('Excel上传错误:', error);
};

const customUpload = async (options: any) => {
  try {
    const formData = new FormData();
    formData.append('file', options.file);
    const response: any = await importVocabulary(formData, props.moduleType);
    if (response.code === 200) {
      options.onSuccess(response);
    } else {
      const error = new Error(response.message || '导入失败');
      options.onError(error);
    }
  } catch (error) {
    options.onError(error);
  }
};

const downloadTemplate = async () => {
  try {
    const response = await downloadVocabularyTemplate();
    const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
    const link = document.createElement('a');
    link.href = url;
    link.download = `${props.moduleTitle}词语导入模板.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败，请重试');
  }
};

const showTemplateHelp = () => {
  ElMessageBox.alert(
    `<div class="template-help">
      <h3>Excel词语导入模板说明</h3>
      <h4>模板格式说明</h4>
      <p>模板包含以下列：</p>
      <ol>
        <li><strong>词语（必填）</strong>：词语的具体内容</li>
        <li><strong>词性（必填）</strong>：词语的词性</li>
        <li><strong>解释（必填）</strong>：词语的解释</li>
        <li><strong>例子（选填）</strong>：词语的例子</li>
        <li><strong>近义（选填）</strong>：词语的近义词</li>
        <li><strong>反义（选填）</strong>：词语的反义词</li>
      </ol>
      <h4>注意事项</h4>
      <ul>
        <li>第一行为表头，请勿修改或删除</li>
        <li>所有必填项不能为空</li>
        <li>文件大小不能超过2MB</li>
        <li>仅支持.xlsx或.xls格式的Excel文件</li>
      </ul>
    </div>`,
    '模板填写说明',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '知道了',
      customClass: 'template-help-dialog'
    }
  );
};

// 表格数据
const loading = ref(false);
const wordList = ref<VocabularyWord[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const selectedWords = ref<VocabularyWord[]>([]);

// 富文本编辑器相关
const definitionEditorRef = createEditorRef();
const examplesEditorRef = createEditorRef();
const mode = 'default';
const editorConfig = getEditorConfig('请输入内容...', '词语积累');
const toolbarConfig = getToolbarConfig();
const handleDefinitionCreated = createEditorCallback(definitionEditorRef);
const handleExamplesCreated = createEditorCallback(examplesEditorRef);

// 表格多选
const handleSelectionChange = (selection: VocabularyWord[]) => {
  selectedWords.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedWords.value.length === 0) return;
  try {
    await ElMessageBox.confirm(`确认删除选中的${selectedWords.value.length}个词语吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const ids = selectedWords.value.map(word => word.id);
    await props.apiModule.batchDeleteVocabulary(ids);
    ElMessage.success('批量删除成功');
    selectedWords.value = [];
    getWordList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 搜索表单
const searchForm = reactive<VocabularyQueryParams>({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
});

// 表单数据
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const isEdit = ref(false);
const wordFormRef = ref<FormInstance>();
const currentWord = ref<VocabularyWord>({} as VocabularyWord);

const wordForm = reactive<VocabularyWord>({
  word: '',
  definition: '',
  partOfSpeech: '',
  examples: '',  // 只存储一个例句，不使用数组
  synonyms: '',
  antonyms: ''
});

// 表单验证规则
const rules = {
  word: [{ required: true, message: '请输入词语', trigger: 'blur' }],
  definition: [{ required: true, message: '请输入解释', trigger: 'blur' }],
  partOfSpeech: [{ required: true, message: '请选择词性', trigger: 'change' }],
  examples: [{ required: false, message: '请输入例句', trigger: 'blur' }]
};

// 获取词语列表
const getWordList = async () => {
  loading.value = true;
  try {
    // 更新searchForm的分页参数，确保与当前组件状态一致
    searchForm.pageNum = currentPage.value;
    searchForm.pageSize = pageSize.value;
    
    const res: any = await props.apiModule.getVocabularyList({
      ...searchForm
    });
    // 处理后端返回的数据
    wordList.value = res.data.list.map((item: any) => ({
      ...item
    }));
    total.value = res.data.total;
  } catch (error) {
    console.error('获取词语列表失败:', error);
    ElMessage.error('获取词语列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const searchWords = () => {
  currentPage.value = 1;
  // 确保searchForm的分页参数同步更新
  searchForm.pageNum = 1;
  getWordList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    pageNum: 1,
    pageSize: 10
  });
  currentPage.value = 1;
  pageSize.value = 10;
  getWordList();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  getWordList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getWordList();
};

// 添加词语
const handleAddWord = () => {
  isEdit.value = false;
  Object.assign(wordForm, {
    word: '',
    definition: '',
    partOfSpeech: '',
    examples: '',
    synonyms: '',
    antonyms: ''
  });
  dialogVisible.value = true;
};

// 编辑词语
const editWord = (row: VocabularyWord) => {
  isEdit.value = true;
  Object.assign(wordForm, {
    ...row
  });
  dialogVisible.value = true;
};

// 查看词语详情
const viewWord = (row: VocabularyWord) => {
  currentWord.value = {
    ...row
  };
  viewDialogVisible.value = true;
};

// 删除词语
const deleteWord = (row: VocabularyWord) => {
  ElMessageBox.confirm('确认删除该词语吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await props.apiModule.deleteVocabulary(row.id);
      ElMessage.success('删除成功');
      getWordList();
    } catch (error) {
      console.error('删除词语失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 提交表单
const submitForm = async () => {
  if (!wordFormRef.value) return;
  
  await wordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交的数据
        const submitData = {
          ...wordForm
        };

        if (isEdit.value) {
          await props.apiModule.updateVocabulary(submitData);
          ElMessage.success('更新成功');
        } else {
          await props.apiModule.addVocabulary(submitData);
          ElMessage.success('添加成功');
        }
        dialogVisible.value = false;
        getWordList();
      } catch (error) {
        console.error('保存词语失败:', error);
        ElMessage.error('保存失败');
      }
    }
  });
};

onMounted(() => {
  getWordList();
});
</script>

<style scoped>
.vocabulary-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-buttons {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 10px; /* 添加按钮之间的间距 */
}

.excel-uploader {
  display: flex; /* 将 inline-flex 修改为 flex */
  margin-right: 0; /* 间距由父容器的 gap 控制，这里设置为0 */
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.action-buttons {
  display: flex;
  gap: 5px; /* 按钮之间的间距 */
}

.word-detail {
  padding: 20px;
}

.word-header {
  text-align: center;
  margin-bottom: 20px;
}

.word-title {
  margin: 0 0 15px;
  color: #303133;
  font-size: 24px;
}

.pronunciation {
  color: #909399;
  font-size: 0.8em;
  margin-left: 10px;
}

.word-tags {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  margin: 0;
}

.detail-section {
  padding: 0 10px;
}

.detail-item {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  width: 70px;
  flex-shrink: 0;
}

.detail-content {
  flex: 1;
  color: #303133;
}

.definition-item {
  margin-bottom: 25px;
}

.definition-content {
  line-height: 1.6;
  text-align: justify;
}

.examples-item {
  flex-direction: column;
}

.examples-item .detail-content {
  margin-top: 10px;
}

.example-card {
  margin-bottom: 15px;
}

.example-card:last-child {
  margin-bottom: 0;
}

.example-header {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.example-card :deep(.el-card__header) {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
}

.example-card :deep(.el-card__body) {
  padding: 15px;
  line-height: 1.6;
  color: #303133;
}

.example-tip {
  margin-top: 8px;
}
</style>